package server;
import model.Client;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 监控服务器列表中的数据
 * @author sa
 */
public class ClientMoniter implements Runnable {
	private static final Logger logger = Logger.getLogger(ClientMoniter.class.getName());
	@Override
	public void run() { 
		HashMap<String,Client> clientMap = Service.clientgroup.getClientMap();
		logger.log(Level.INFO, "开始监控客户端连接    当前连接数目"+clientMap.size());
		if(clientMap==null||clientMap.size()<=0)
		{
			//如果长度为0 ，把所有节点的数据库格式修改为未发布
			Service.control.updateAll("2");
		}else
		{
			Iterator<Entry<String, Client>> it=clientMap.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, Client> entry =it.next();
				String nodeidentity=entry.getKey();
				Client ct=entry.getValue();
				//判断哪个通道失效，然后从队列中剔除
				if(ct.getMachineChannel()==null
						||(!ct.getMachineChannel().isActive()
							&&!ct.getMachineChannel().isOpen()
							&&!ct.getMachineChannel().isRegistered()
							&&!ct.getMachineChannel().isWritable()))
				{
					Service.control.NoticeClosed(ct);
					Service.clientgroup.removeChannel(nodeidentity);
					break;
				}
			}
		}
	}
}